#!/bin/bash

time="$(date +%Y"-"%m"-"%d"_"%k":"%M":"%S)"
cd $(cd `dirname $0`; pwd)

echo "$time begin to install--------------------------nginx "
UANME_el6=`uname -a | grep el6`
UANME_el7=`uname -a | grep el7`
if [[ -n "$UANME_el6" ]]; then
	echo "CentOS 6 installing..."
	sed -i "s/OSRELEASE/6/g" nginx.repo
	chkconfig iptables off
	service iptables stop
elif [[ -n "$UANME_el7" ]]; then
	echo "CentOS 7 installing..."
	sed -i "s/OSRELEASE/7/g" nginx.repo
	# close SELinux
	setenforce 0
	systemctl disable firewalld
	systemctl stop firewalld
else
	echo "ERROR! OS is not support!"
	exit -1
fi
test -f /etc/yum.repos.d/nginx.repo && rm -f /etc/yum.repos.d/nginx.repo
cp nginx.repo /etc/yum.repos.d/
yum -y install nginx
isNginxInstalled=`rpm -qa | grep nginx`
if [[ -z "$isNginxInstalled" ]]; then
	yum -y install nginx
fi

if [[ -n "$UANME_el6" ]]; then
	echo "config auto start in CentOS 6"
	chkconfig nginx on
elif [[ -n "$UANME_el7" ]]; then
	echo "config auto start in CentOS 7"
	systemctl enable nginx
fi


nginx_base="/etc/nginx"
rm -rf $nginx_base/conf.d
rm -f $nginx_base/nginx.conf
cp ./nginx.conf $nginx_base/
cp ./server.* $nginx_base/
cp -r ./module $nginx_base/
service nginx start

nginx_server_process=`ps aux | grep nginx | grep -v grep | grep master`
if [ ! -z "$nginx_server_process" ]; then
	echo "nginx installed SUCCESS!"
	nginxPid=`cat /var/run/nginx.pid`
	echo "nginx(pid  $nginxPid) is running..."
else
	echo "ERROR!! nginx installed failed!"
fi